package com.db.chat.logging;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Logger blocks execution while writing to file
 */

public class FileSyncLogger extends AbstractLogger {

    private BufferedWriter writer;

    public FileSyncLogger(@NotNull String fileName) throws LoggerException {
        try {
            writer = new BufferedWriter(new FileWriter(new File(fileName), true));
        } catch (IOException e) {
            throw new LoggerException("File can not be created / appended");
        }
    }

    /**
     * Uses BufferedWriter to write to file
     * On error nothing happens
     * @param text - text to write
     */

    @Override
    public void write(@NotNull String text) {
        synchronized (this) {
            try {
                writer.write(text);
                writer.flush();
            } catch (IOException e) {
                //nothing to do
            }
        }



    }

    @Override
    public void close() throws IOException {
        writer.close();
    }
}
